package com.rules.admin.expression;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;

public class ExecuteExpression implements Expression {
   private String objectName;
   private String methodName;
   private List<Expression> paramExpressions = Lists.newArrayList();
   private Integer code;
   private String message;

   public void accept(ExpressionVisitor visitor) {
      visitor.vistor(this);
   }

   public ExecuteExpression(String objectName, String methodName) {
      this.objectName = objectName;
      this.methodName = methodName;
   }

   public ExecuteExpression(String objectName, String methodName, Expression... paramExpressions) {
      this.objectName = objectName;
      this.methodName = methodName;
      this.paramExpressions = Arrays.asList(paramExpressions);
   }

   public ExecuteExpression(String methodName, Expression... paramExpressions) {
      this.methodName = methodName;
      this.paramExpressions = Arrays.asList(paramExpressions);
   }

   public ExecuteExpression(String objectName, String methodName, List<Expression> paramExpressions) {
      this.objectName = objectName;
      this.methodName = methodName;
      this.paramExpressions = paramExpressions;
   }

   public ExecuteExpression(Integer code, String message) {
      this.code = code;
      this.message = message;
   }

   public String getObjectName() {
      return this.objectName;
   }

   public void setObjectName(String objectName) {
      this.objectName = objectName;
   }

   public String getMethodName() {
      return this.methodName;
   }

   public void setMethodName(String methodName) {
      this.methodName = methodName;
   }

   public List<Expression> getParamExpressions() {
      return this.paramExpressions;
   }

   public void setParamExpressions(List<Expression> paramExpressions) {
      this.paramExpressions = paramExpressions;
   }

   public void addParam(Expression expression) {
      this.paramExpressions.add(expression);
   }

   public String toString() {
      if (this.message == null) {
         StringBuilder builder = null;
         if (StringUtils.isEmpty(this.objectName)) {
            builder = new StringBuilder();
         } else {
            builder = new StringBuilder(this.objectName);
            builder.append(".");
         }

         builder.append(this.methodName).append("(").append(Joiner.on(",").join(this.paramExpressions)).append(")");
         return builder.toString();
      } else {
         return "throw new Exception(" + this.message + ")";
      }
   }
}
